package com.guashu.springbootdistributedid.demo;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

public class TransTxtToPng {

    public static void main(String[] args) {
        String inputTXTPath = "E:\\国银租赁\\观微文档\\国银金租_观微大数据风控开发项目_软件需求规格说明书-20240118.files\\国银金租_观微大数据风控开发项目_软件需求规格说明书-202401189919.txt";
        String outputPNGPath = "E:\\国银租赁\\观微文档\\国银金租_观微大数据风控开发项目_软件需求规格说明书-20240118.files\\output.png";
        int fontSize = 8; // 字体大小

        try {
            // 读取TXT文件
            BufferedReader reader = new BufferedReader(new FileReader(inputTXTPath));
            String line;
            StringBuilder text = new StringBuilder();
            while ((line = reader.readLine()) != null) {
                text.append(line).append("\n");
            }
            reader.close();

            // 获取文本的行数和列数
            String[] lines = text.toString().split("\n");
            int height = lines.length;
            int width = lines[0].length();

            // 创建BufferedImage对象
            BufferedImage image = new BufferedImage(width * fontSize, height * fontSize, BufferedImage.TYPE_INT_RGB);
            Graphics g = image.getGraphics();
            g.setColor(Color.WHITE);
            g.fillRect(0, 0, image.getWidth(), image.getHeight());
            g.setColor(Color.BLACK);
            g.setFont(new Font("Monospaced", Font.PLAIN, fontSize));
            FontMetrics fm = g.getFontMetrics();

            // 将ASCII字符绘制到图像中
            for (int y = 0; y < height; y++) {
                for (int x = 0; x < width; x++) {
                    char ch = lines[y].charAt(x);
                    g.drawString(Character.toString(ch), x * fontSize, (y + 1) * fontSize - fm.getDescent());
                }
            }

            // 保存图像为PNG文件
            ImageIO.write(image, "PNG", new File(outputPNGPath));

            System.out.println("TXT文件已转换为PNG图像：" + outputPNGPath);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
